<?php
namespace Home\Controller;
use Think\Controller;
class JieController extends CommonController {

    public function api()
    {
        $sql = "select t1.*,t2.nickname,t2.face,t3.cname from question t1 inner join user t2 on t1.uid=t2.uid inner join category t3 on t1.cid=t3.cid where t1.top<>'1' order by create_time desc limit 10";

        $question = M()->query($sql);

        sleep(3);

        echo json_encode($question);
    }
    public function index(){

<<<<<<< HEAD
        // $test = M('test');

        // //  在User模型中启动事务
        // $test->startTrans();
        // // 进行相关的业务逻辑操作
        // // 
        // $data = ['name'=>'小红e'];

        // $test->add($data);

        // $data = ['name'=>'小红r'];

        // $test->add($data);
        

        // $data = ['name'=>'小红g'];

        // $test->add($data);
        
        // $test->commit(); 

        // exit;
        







        // // if (操作成功){
        // //     // 提交事务
        // //    $test->commit(); 
        // // }else{
        // //    // 事务回滚
        // //    $test->rollback(); 
        // // }

        // exit;

        // $id = $_GET['id'];
        // 
        // $id = I('get.id','','int');

        // var_dump($id);

        // $sql = "select * from question where qid='{$id}#'";


        // $sql = M()->where(['qid'=>$qid])->select();

        // var_dump($sql);

        // // var_dump($sql);exit;

        // // $res = M()->query($sql);


        // var_dump($res);exit;








=======
>>>>>>> parent of dba4162... fix
    	$qid = I('get.id');

        $uid = $_SESSION['uid'];

    	M('question')->where(['qid'=>$qid])->setInc("view_num");

    	$sql = "select t1.*,t2.nickname,t2.face from question t1 left join user t2 on t1.uid=t2.uid where t1.qid='{$qid}'";

    	$question = M()->query($sql);


    	$hotQues = M('question')->field('qid,title,answer_num')->order("answer_num desc")->limit(10)->select();

    	// M('question t1')->join('user t2 on t1.uid=t2.uid')->where("t1.qid='{$qid}'")->select();
        
        $sql = "select t1.aid,t1.content,t1.zan_num,t1.create_time,t1.status,t2.nickname,t2.face,t2.uid from answer t1 inner join user t2 on t1.uid=t2.uid where t1.qid='{$qid}'";

        $answers = M()->query($sql);


        foreach ($answers as $k => $row) {
            $zan = M('zan')->where(['aid'=> $row['aid'],'uid'=>$uid])->find();
            if($zan){
               $answers[$k]['is_zan']=1; 
            }else{
                $answers[$k]['is_zan']=0; 
            }

        }
        
        $collect = M('collect')->where(['qid'=> $qid,'uid'=>$uid])->find();




        $appId='wxbac82045a637c02e'; // 必填，公众号的唯一标识
        $timestamp=time(); // 必填，生成签名的时间戳
        $nonceStr=$this->getNonceStr(16); // 必填，生成签名的随机串

        $access_token = $this->get_access_token();

        $jsapi_ticket = $this->get_jsapi_ticket($access_token);


        $url = "http://1o533n8683.imwork.net".U('home/jie/index',array('id'=>$qid));

        $str ="jsapi_ticket=".$jsapi_ticket."&noncestr=".$nonceStr."&timestamp=".$timestamp."&url=".$url ;

        $signature=sha1($str);// 必填，签名，见附录1

        // var_dump($appId,$access_token,$jsapi_ticket,$timestamp,$nonceStr,$signature);exit;


        $this->assign('appId',$appId);
        $this->assign('timestamp',$timestamp);
        $this->assign('nonceStr',$nonceStr);
        $this->assign('signature',$signature);
        $this->assign('url',$url);

        $this->assign('collect',$collect);
        $this->assign('answers',$answers);
    	$this->assign('hotQues',$hotQues);
    	$this->assign('ques',current($question));
        $this->assign('title',current($question)['title']);
        $this->display();
    }

    public function get_jsapi_ticket($access_token)
    {
        if(!S('jsapi_ticket')){
            $url ="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";

            $data = file_get_contents($url);

            $data = json_decode($data,true);

            S('jsapi_ticket',$data['ticket'],7200);
            return S('jsapi_ticket');
        }else{
            return S('jsapi_ticket');
        }
        
    }

    public function get_access_token()
    {
        if(!S('access_token')){
            $url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxbac82045a637c02e&secret=7c320fea54e77a01fcc59ff7060b04e2";

            $data = file_get_contents($url);

            $data = json_decode($data,true);

            S('access_token',$data['access_token'],7200);
            return S('access_token');
        }else{
            return S('access_token');
        }
        
    }

    public function getNonceStr($num=16)
    {
       $str ="QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890";
       $temp ='';

       for ($i=0; $i < $num; $i++) { 
          $temp .=$str[mt_rand(0,strlen($str)-1)];
       }

       return $temp;
    }
    public function add(){

        // if(!isset($_SESSION['uid'])){
        //     $this->error("你还没有登录，请先登录",U('home/login/index'));
        // }
        
    	$question = D('vercode')->getOne();
    	$category = M('category')->select();


    	$tempArr = array();

    	foreach ($category as $row) {
    		if($row['fid']==0){
    			$tempArr[]= $row;
    		}
    	}

    	foreach ($tempArr as $key => $father) {
    		foreach ($category as $son) {
    			if($son['fid']==$father['cid']){
    				$tempArr[$key]['son'][]=$son;
    			}
    		}
    	}
    	// echo "<pre>";
    	// print_r($tempArr);

    	// // var_dump($category);
    	// exit;
    	$this->assign('category',$tempArr);
    	$this->assign('question',$question);
    	$this->display();
    }

    public function ajaxadd()
    {
    	$data = I('post.');

    	$res = D('vercode')->checkCode($data['vercode']);

    	if(!$res){
    		$this->ajaxReturn(['error'=>1,'info'=>"人类验证不通过"]);
    	}

    	$data['uid'] = $_SESSION['uid'];

    	$data['create_time'] = time();

    	$qid  = M('question')->add($data);

    	$this->ajaxReturn(['error'=>0,'info'=>'发布成功','url'=>U('home/jie/index',array('id'=>$qid))]);


    }

    public function upload()
    {
    	$upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './Uploads/pic/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件 
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            echo "失败";
        }else{// 上传成功
            // var_dump($info);
            $face = __ROOT__."/Uploads/pic/".$info['file']['savepath'].$info['file']['savename'];

            $arr = array(
            	'code'=>0,
            	'msg'=>'成功',
            	'data'=>array(
            		'src'=>$face,
            		'title'=>'图片名称'
            		)
            	);
            echo json_encode($arr);         
            
        }
    }

    public function answeradd()
    {
        $data = I("post.");
        $data['uid'] = $_SESSION['uid'];
        $data['create_time'] = time();

        if(M('answer')->add($data)){
            $this->ajaxReturn(['error'=>0,'info'=>'发布成功']);
        }else{
            $this->ajaxReturn(['error'=>1,'info'=>'发布失败']);
        }
    }
    public function collect()
    {
        $qid = I('post.qid');
        $uid = $_SESSION['uid'];


        $res = M('collect')->where(['qid'=> $qid,'uid'=>$uid])->find();

        if(!$res){
            M('collect')->add(['qid'=> $qid,'uid'=>$uid]); 
            $this->ajaxReturn(['error'=>0,'info'=>'收藏成功']);
        }else{
            M('collect')->where(['qid'=> $qid,'uid'=>$uid])->delete(); 
            $this->ajaxReturn(['error'=>1,'info'=>' 取消收藏']);
        }
    }


    public function zan()
    {
        $aid = I('post.aid');
        $uid = $_SESSION['uid'];


        $res = M('zan')->where(['aid'=> $aid,'uid'=>$uid])->find();

        if(!$res){
            M('zan')->add(['aid'=> $aid,'uid'=>$uid]); 
            M('answer')->where(['aid'=>$aid])->setInc("zan_num");
            $this->ajaxReturn(['error'=>0,'info'=>'点赞成功']);
        }else{
            M('zan')->where(['aid'=> $aid,'uid'=>$uid])->delete();
            M('answer')->where(['aid'=>$aid])->setDec("zan_num"); 
            $this->ajaxReturn(['error'=>1,'info'=>' 取消点赞']);
        }
    }
}